<?php
declare(strict_types=1);

namespace app\model;


namespace app\model;


use think\Model;

class BaseModel extends Model
{
    public $with = [];

    public function data_add($data, $isSaveAll = false)
    {
        if ($isSaveAll) {
            return $this->saveAll($data);
        }
        $res = $this->save($data);
        $pk = $this->getPk();
        if (!$pk) {
            return $res;
        }
        return $res ? $this->$pk : 0;
    }

    public function data_update($condition, $data, $isSaveAll = false)
    {
        if ($isSaveAll) {
            return $this->where($condition)->saveAll($data);
        }
        try {
            $res = $this->update($data, $condition);
        } catch (\Exception $e) {
            bs_log($e->getMessage(), 'error', 'data_update.log');
            return false;
        }
        return $res;
    }

    //直接删除
    public function data_del($condition)
    {
        if (!$condition) return false;
        return self::where($condition)->delete();
    }

    //软删除
    public function data_del_soft($condition, $field = 'del_time', $value = 1)
    {
        if (!$condition) return false;
        return $this->update([$field => $value], $condition);
    }


    public function data_get($condition, $field = '*', $order = '')
    {
        $data = $this->with($this->with)->order($order)->where($condition)->field($field)->find();
        return $data;
    }

    public function data_count($condition, $field = '*', $group = '')
    {
        return $this->where($condition)->group($group)->count($field);
    }

    public function data_sum($condition, $field = '*')
    {
        return $this->where($condition)->sum($field);
    }

    public function get_value($condition, $field, $order = '')
    {
        return self::where($condition)->order($order)->value($field);
    }

    public function data_list($condition = [], $field = '*', $order = 'id desc', $page = 1, $pageSize = 10)
    {
        return $this
            ->where($condition)
            ->field($field)
            ->with($this->with)
            ->order($order)
            ->page(intval($page), intval($pageSize))
            ->select();
    }

    public function data_list_nopage($condition = [], $field = '*', $order = '', $group = '')
    {
        return $this
            ->where($condition)
            ->field($field)
            ->with($this->with)
            ->group($group)
            ->order($order)
            ->select()
            ->toArray();
    }
}
